package miniapp

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/spf13/cast"
	"hr/config"
	"net/http"
)

// GetCode2Session 登录凭证校验
func GetCode2Session(code string) (string, error) {
	resp, err := http.DefaultClient.Get(fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", config.AppConfig.Miniapp.Appid, config.AppConfig.Miniapp.Secret, code))
	if err != nil {
		return "", err
	}
	var jMap map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&jMap)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if _,ok:=jMap["errcode"] ;!ok || jMap["errcode"] == 0 {
		openId, _ := jMap["openid"]
		return cast.ToString(openId), nil
	} else {
		errcode := cast.ToString(jMap["errcode"])
		errmsg := cast.ToString(jMap["errmsg"])
		err = errors.New(errcode + ":" + errmsg)
		return "", err
	}
}